﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;

public class CommandBuffer_Example2 : MonoBehaviour
{
    public Material blurMaterial;
    public Material playerReplaceMaterial;
    public Renderer[] playerRenderers;
    public int sampleNum = 3;
    public float blurRadius = 0.2f;

    CommandBuffer mStencilFixCommandBuffer;
    CommandBuffer mBlurCommandBuffer;
    int mBlurTempRT1;


    void OnEnable()
    {
        mStencilFixCommandBuffer = new CommandBuffer();
        mStencilFixCommandBuffer.name = "StencilFix";

        for (int i = 0; i < playerRenderers.Length; i++)
        {
            var item = playerRenderers[i];
            mStencilFixCommandBuffer.DrawRenderer(item, playerReplaceMaterial, 0, -1);
        }

        Camera.main.AddCommandBuffer(CameraEvent.AfterSkybox, mStencilFixCommandBuffer);

        mBlurCommandBuffer = new CommandBuffer();
        mBlurCommandBuffer.name = "Blur";
        mBlurTempRT1 = Shader.PropertyToID("BlurTempRT1");
        mBlurCommandBuffer.GetTemporaryRT(mBlurTempRT1, -2, -2, 0);
        mBlurCommandBuffer.Blit(BuiltinRenderTextureType.CameraTarget, mBlurTempRT1);

        for (int i = 0; i < sampleNum - 1; i++)
        {
            mBlurCommandBuffer.Blit(mBlurTempRT1, BuiltinRenderTextureType.CameraTarget, blurMaterial);
            mBlurCommandBuffer.Blit(BuiltinRenderTextureType.CameraTarget, mBlurTempRT1);
        }

        mBlurCommandBuffer.Blit(mBlurTempRT1, BuiltinRenderTextureType.CameraTarget, blurMaterial);

        Camera.main.AddCommandBuffer(CameraEvent.BeforeImageEffects, mBlurCommandBuffer);
    }

    void Update()
    {
        blurMaterial.SetFloat("_BlurRadius", blurRadius);
    }

    void OnDisable()
    {
        mBlurCommandBuffer.ReleaseTemporaryRT(mBlurTempRT1);

        Camera.main.RemoveCommandBuffer(UnityEngine.Rendering.CameraEvent.BeforeReflections, mBlurCommandBuffer);
        mBlurCommandBuffer.Dispose();

        Camera.main.RemoveCommandBuffer(UnityEngine.Rendering.CameraEvent.AfterLighting, mStencilFixCommandBuffer);
        mStencilFixCommandBuffer.Dispose();
    }
}
